import React from 'react'
import { View, StyleSheet, Text } from 'react-native'
import CustomButton from 'src/components/button/CustomButton'
import CommonInputPage from '../common-input-page'
import { HEIGHT, NAVIGATIONBAR_HEIGHT, ScaleS, ScaleT } from 'src/utils/ScreenUtil'
import debounce from 'lodash/debounce'
import CustomFlatList from '../../../components/custom-flat-list/index'

export default class CommonInputListPage extends CommonInputPage {
  constructor (props) {
    super(props)
    this.state = {
      ...this.state,
      dataArr: []
    }
    this.associativeRequest = this.params.associativeRequest
  }

  renderBottomView () {
    const {
      dataArr
    } = this.state
    return (
      <CustomFlatList
        pullDown={false}
        pullUp={false}
        data={dataArr}
        renderItem={this._renderItem}
        style={styles.list}
        keyExtractor={(item) => item.name}/>
    )
  }

  _renderItem = ({ item, index }) => {
    return (
      <CustomButton style={styles.listItem} key={index} onPress={this._itemClick} params={{ item }}>
        <View style={styles.line}/>
        <Text style={styles.listLabel}>{item.name}</Text>
      </CustomButton>
    )
  }

  _itemClick = ({ item }) => {
    this.setState({
      editValue: item.name,
      count: item.name.length,
      dataArr: [],
      checked: true
    })
  }

  onChangeText (editValue) {
    console.info(editValue)
    super.onChangeText(editValue)
    this.debounceTextChange(editValue)
  }

  debounceTextChange = debounce((editValue) => {
    if (this.associativeRequest) {
      this.associativeRequest(editValue).then((data) => {
        console.info(data)
        this.setState({
          dataArr: data
        })
      })
    }
  }, 500, { maxWait: 1000 })

  componentWillUnmount () {
    super.componentWillUnmount()
    this.debounceTextChange.cancel()
  }
}

const styles = StyleSheet.create({
  list: {
    height: (HEIGHT - NAVIGATIONBAR_HEIGHT - ScaleS(200))
  },
  listItem: {
    height: ScaleS(65)
  },
  line: {
    height: ScaleS(1),
    backgroundColor: '#EFEFEF'
  },
  listLabel: {
    lineHeight: ScaleS(64),
    color: '#666666',
    fontSize: ScaleT(16),
    fontWeight: '400',
    marginHorizontal: ScaleS(20)
  }
})
